<?php

namespace app\services;


use app\traits\Page;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserLevel;
use plugin\admin\app\model\UserTeam;
use plugin\admin\app\model\UserTeamMonthData;
use plugin\admin\app\model\UserUpline;
use support\Db;

class UserTeamService
{
    public static function children($page, $length = 10, $isRecommend = true, $level = 1)
    {
        $offset = ($page - 1) * $length;

        $query = Db::table('wa_users', 'u')
            ->select(['u.id', 'u.level', 'up.nickname', 'up.avatar', 'u.join_time'])
            ->join(Db::raw('wa_user_profiles as up'), 'up.user_id', '=', 'u.id', 'left');

        if ($isRecommend) {
            $query->where('u.parent_id', get_user_id());
        } else {
            if ($level > 0) {
                $query->where('u.level', $level);
            }

            $children = UpLineService::children(get_user_id());
            $userIds = array_column($children, 'user_id');

            if (count($userIds) > 0) {
                $query->whereIn('u.id', $userIds);
            } else {
                $query->where('u.id', 0);
            }
        }

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->orderByDesc('u.join_time')->get()->toArray();

        foreach ($list as $key=>$item) {
            $item = json_decode(json_encode($item), true);
            $item['level_text'] = UserLevel::getLevelText($item['level']);

            if ($isRecommend) {
                $item['is_buy'] = OrderService::getRangeTimeGiftOrderCount(date('Y-m-01 00:00:00'), date('Y-m-d H:i:s'), $item['id']) > 0;
            }

            $list[$key] = $item;
        }

        return Page::wrap($totalCount, $page, $length, $list);
    }

    public static function teamInfo()
    {
        return UserTeam::where('user_id', get_user_id())->first()->toArray();
    }

    public static function addOrderCount($order)
    {
        $user = User::where('id', $order['user_id'])->first();

        if ($user['parent_id'] == 0) {
            return;
        }

        $parentId = $user['parent_id'];

        UserTeam::where('user_id', $parentId)->increment('recommend_order_count', 1);
        UserTeam::where('user_id', $parentId)->increment('current_month_recommend_order_count', 1);

        $parentIds = UpLineService::get($order['user_id']);

        if (count($parentIds) > 0) {
            UserTeam::whereIn('user_id', $parentIds)->increment('team_order_count', 1);
            UserTeam::whereIn('user_id', $parentIds)->increment('current_month_order_count', 1);
        }

        //如果当月直推订单数满足条件，则发放优惠券，每月只发放一次
        $parentUserTeamInfo = UserTeam::where('user_id', $parentId)->first();

        $recommendCountLimit = ConfigService::get('extra_reward_recommend_count');
        $needOrderCount = $recommendCountLimit;

        if ($parentUserTeamInfo['current_month_recommend_order_count'] == $needOrderCount) {
            $coupon = CouponService::giftCoupon();

            if ($coupon) {
                try {
                    UserCouponService::give($coupon['id'], $parentId);

                } catch (\Exception $e) {
                    echo $e->getMessage() . $e->getTraceAsString();
                }
            }
        }
    }

    public static function clearCurrentMonthRecommendOrderCount()
    {
        $teams = UserTeam::where('current_month_recommend_order_count', '>', 0)->get()->toArray();

        foreach ($teams as $team) {
            $month = date('Y-m', strtotime('-1 month'));

            if (UserTeamMonthData::where('day', $month)->where('user_id', $team['user_id'])->count() == 0) {
                UserTeamMonthData::insert([
                    'user_id' => $team['user_id'],
                    'day' => $month,
                    'recommend_order_count' => $team['current_month_recommend_order_count'],
                    'order_count' => $team['current_month_order_count'],
                ]);

                UserTeam::where('id', $team['id'])->update(['current_month_recommend_order_count' => 0, 'current_month_order_count' => 0]);
            }
        }

    }
}